"""
主题: 定义接口或者抽象基类
问题: 你想定义一个接口或抽象类，并且通过执行类型检查来确保子类实现了某些特定的方法
提示 : 
    Python的本质是一门动态编程语言，其目的就是给你更多灵活性， 强制类型检查或让你代码变得更复杂，这样做无异于舍本求末
"""

from abc import ABCMeta, abstractmethod


class IStream(metaclass=ABCMeta):
    @abstractmethod
    def read(self, maxbytes=-1):
        pass

    @abstractmethod
    def write(self, data):
        pass


class SocketStream(IStream):
    def read(self, maxbytes=-1):
        ''''''
        pass

    def write(self, data):
        ''''''
        pass


class A(metaclass=ABCMeta):
    @property
    @abstractmethod
    def name(self):
        pass

    @name.setter
    @abstractmethod
    def name(self, value):
        pass

    @classmethod
    @abstractmethod
    def method1(cls):
        pass

    @staticmethod
    @abstractmethod
    def method2():
        pass

def serialize(obj, stream): #NOSONAR
    '''抽象基类的一个主要用途是在代码中检查某些类是否为特定类型，实现了特定接口'''
    if not isinstance(stream, IStream):
        raise TypeError('Expected an IStream')

def recipe1():
    import io

    # Register the built-in I/O classes as supporting our interface
    IStream.register(io.IOBase)

    # Open a normal file and type check
    f = open('../somefile.txt')
    print(f"{isinstance(f, IStream) = }") # Returns True

def main():
    print('recipe1'.center(20, '*'))
    recipe1()

if __name__ == '__main__':
    main()          